// pages/customer_product_details/actionSheet/index.js
import {
  request,
} from '../../../utils/requestUtils';
import {
  debounce
} from 'miniprogram-licia'
import { userBehavior } from '../../../behaviors/userBehavior'

Component({
  behaviors: [userBehavior],
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    carNum: 0,
    show: false,
    goods: {}, // 商品信息
    type: '', // 操作类型：1.加入购物车；2.立即购买
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 取消
    cancelHandler() {
      this.setData({
        show: false
      })
    },
    async getCartNum() {
      const result = await request({
        url: `/bus/customer/cart/cartNum`,
        method: "GET"
      })
      if (result.data.code == 200) {
        this.setCarNum(result.data.data)
      }
    },
    //确认
    async submitHanddler() {
      if (this.data.type == '1') {
        const result = await request({
          url: `/bus/customer/cart`,
          method: "POST",
          data: {
            productId: this.data.goods.id,
            productCode: this.data.goods.productCode,
            carNum: this.data.carNum,
            checked: 2,
            remark: this.data.goods.remark,
            merchantId: this.data.goods.stallId,
            merchantName: this.data.goods.stallName
          }
        })
        if (result.data.code == 200) {
          this.getCartNum()
          wx.switchTab({
            url: '/pages/customer_shop_cart/index',
          })
        }
      } else {
        // 立即购买
        console.log('carNum', this.data.carNum)
        if (!this.data.carNum || this.data.carNum == 0) {
          wx.showToast({
            title: '请选择购买数量',
            icon: 'none',
            duration: 2000,
            mask: true
          })
          return
        }
        wx.navigateTo({
          url: '/pages/customer_pay/index?good='+ encodeURIComponent(JSON.stringify({
            productId: this.data.goods.id,
            carNum: this.data.carNum,
            remark: this.data.goods.remark
          }))
        })
      }

    },
    //初始化
    addhow(e, data) {
      this.setData({
        goods: data,
        type: e.target.dataset.type,
        show: true,
        carNum: 0
      })
    },
    // 监听是否更改了购买数量
    onChangeGoodsCount: debounce(async function (event) {
      this.setData({
        carNum: event.detail
      })
    }, 500),
    onTextAreaChange(e) {
      this.setData({
        'goods.remark': e.detail.value
      })
    }
  }
})